package org.ogv.usada.models;

import java.util.ArrayList;

import org.ogv.OGV;
import org.ogv.collision.BoundingSphere;

import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Pool;

public class Leaf {
	public int				id;
	public LeafDef 			leafDef;
	public Sprite			leafSprite;
	public BoundingSphere 	bSphere;
	public Sound			slicedSound;
	
	public float 			vx, vy, vAngular;
	
	////Object Management
	private static Pool<Leaf> _POOL = new Pool<Leaf>() {
		@Override
		protected Leaf newObject() {
			return new Leaf();
		}
	};	
	public static void clearPool() 	{ _POOL.clear(); }
	public static Leaf obtain() 	{ return _POOL.obtain(); }
	public void free()				{ bSphere.free(); bSphere = null; _POOL.free(this); } 
	private Leaf() {}
	

	
	public Leaf init(int id, float x, float y, float vx, float vy, float vAngular, int imgFile) {
		leafDef 	= Content.$().leaves[this.id = id];
		leafSprite	= new Sprite(OGV.asset.getTextureRegion(leafDef.imageFiles[imgFile]));
		bSphere		= BoundingSphere.obtain().init(0, 0, leafDef.hitRadius, (byte)0);
		slicedSound	= OGV.asset.get(leafDef.slicedSound, Sound.class);
		
		//positions
		leafSprite.setPosition(x, y);
		this.vx 		= vx;
		this.vy 		= vy;
		this.vAngular 	= vAngular;
		bSphere.x 		= leafSprite.getX();
		bSphere.y 		= leafSprite.getY();
		
		return this;
	}

	public Leaf init(int id, float x, float y, float vx, float vy, float vAngular) {
		return init(id, x, y, vx, vy, vAngular, 0);
	}
	
	public void update(float deltaTime) {
		//update velocity
		vy += GP.$().GAME_GRAVITY * deltaTime;
		
		//update sprite position
		leafSprite.setPosition(leafSprite.getX() + vx * deltaTime, leafSprite.getY() + vy * deltaTime);
		leafSprite.rotate(vAngular * deltaTime);
		
		//update bounds
		bSphere.x = leafSprite.getX() + (leafSprite.getWidth()/2);
		bSphere.y = leafSprite.getY() + (leafSprite.getHeight()/2);
	}
	
	public void getSlicedLeaves(ArrayList<SlicedLeaf> out, Pot destPot) {
		for (int i = 1; i < leafDef.imageFiles.length; ++i) {
			SlicedLeaf l = SlicedLeaf.obtain();
			l.init(
				this.id, 
				leafSprite.getX() + GP.$().RANDOM.nextFloat() * bSphere.radius * 2 - bSphere.radius, 
				leafSprite.getY() + GP.$().RANDOM.nextFloat() * bSphere.radius * 2 - bSphere.radius, 
				destPot.getRandMouthPosX() - leafSprite.getWidth()/4,
				destPot.getRandMouthPosY(),
				vAngular, 
				i
			);
			out.add(l);
		}
	}
	
	public void draw(SpriteBatch sb) {
		leafSprite.draw(sb);
		if(GP.$().DEBUG_DRAW) bSphere.debugDraw(sb);
	}
}
